<template>
  <div class="queryTable-box">
    <el-table
      ref="multipleApiTable"
      v-loading="loading"
      :height="displayContent['height']"
      border
      :data="tableList"
      empty-text="暂时没有数据"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      :row-key="displayContent['rowKey'] ? displayContent['rowKey'] : 'id'"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        v-if="displayContent['selection']"
        :fixed="displayContent['selectionFixed']"
        :reserve-selection="displayContent['reserveSelection'] ? displayContent['reserveSelection'] : false"
        type="selection"
        width="55"
        align="center"
      />
      <el-table-column
        v-if="displayContent['index']"
        :fixed="displayContent['indexFixed']"
        label="序号"
        width="80px"
        align="center"
        type="index"
      ></el-table-column>

      <el-table-column
        v-for="(item, index) in tableConfiguration"
        :key="index"
        :prop="item.prop ? item.prop : ''"
        :label="item.label"
        :width="item.width ? item.width : ''"
        :min-width="item.minWidth ? item.minWidth : ''"
        :align="item.align"
        show-overflow-tooltip
        :fixed="item.fixed ? item.fixed : false"
      >
        <template v-slot="scope">
          <!-- 插槽 放一些不好写的东西 -->
          <div v-if="item.sockets">
            <slot :scope="scope" :name="item.prop"></slot>
          </div>

          <!-- 正常数据 -->
          <span v-else>
            {{ scope.row[item.prop] }}
          </span>
        </template>
      </el-table-column>
    </el-table>

    <div class="el_pagination_box" v-if="displayContent.paginationShow">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="inquiryForm.page"
        :page-sizes="[10, 20, 30, 40, 50, 100]"
        :page-size="inquiryForm.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        background
        hide-on-single-page
      ></el-pagination>
    </div>

    <!-- 编辑 新增 弹框 -->
    <el-dialog :title="popConfing.title" :visible.sync="dialogVisible" :width="popConfing.width">
      <el-form :model="ruleForm" :rules="popConfing.rules" ref="ruleForm" label-width="auto" class="demo-ruleForm">
        <el-form-item
          :label="item.label"
          :prop="item.prop"
          v-for="(item, index) in popConfing.formList"
          :key="index"
        >
          <!-- 普通输入框  -->
          <el-input
            v-if="item.type == 'input'"
            :placeholder="'请输入' + item.label"
            v-model="ruleForm[item.value]"
          ></el-input>

          <!-- 普通下拉选  -->
          <el-select
            v-if="item.type == 'select'"
            v-model="ruleForm[item.value]"
            :placeholder="'请输入' + item.label"
          >
            <el-option :label="e.label" :value="e.value" v-for="(e, i) in item.option" :key="i"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="resetForm('ruleForm')">取 消</el-button>
        <el-button type="primary" @click="submitForm('ruleForm')">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
/*
 *  表格的配置*************************
 *  height: '50vh', // 表格高度
 *  indexFixed: true, // 数字是否左浮动
 *  selectionFixed: true, // 多选框是否左浮动
 *  selection: false, // 是否显示多选框
 *  index: true, // 是否显示数字
 *  paginationShow: true // 是否展示分页
 *  rowKey: 'no', // 用来回显多选或者其他
 *  reserveSelection: true // 在数据更新之后保留之前选中的数据（需指定 row-key）
 */
export default {
  props: {
    tableConfiguration: {
      type: Array,
      default: true
    },
    displayContent: {
      type: Object,
      default: true
    },
    formData: {
      type: Object,
      default: true
    },
    //是否是弹窗===== 防止调用两次接口
    isPop: {
      type: Boolean,
      default: false // 默认值
    },
    api: {
      default: true
    },
    //后端返回参数的层级
    zData: {
      type: String,
      default: 'data'
    },

    // 总条数路径（可自定义）
    zDataTotal: {
      type: String,
      default: 'count'
    }
  },
  components: {},
  created() {},
  mounted() {
    if (this.api && !this.isPop) {
      this.getTable();
    }
  },
  data() {
    return {
      loading: false, //等待中
      //表格传给后端的数据
      inquiryForm: {
        page: 1,
        limit: 10
      },
      total: 0,
      //表格数据
      tableList: [
        // {
        //   a1: '测试1测试1测试1测试1测试1测试1测试1测试1测试1测试1测试1测试1',
        //   a2: '测试1',
        //   a3: '测试1',
        //   a4: '测试1'
        // }
      ],

      //新增编辑弹框
      dialogVisible: false,
      //弹框配置文件
      popConfing: {
        title: '', //弹框名称
        width: '',
        api1: null, //新增api
        formList: [
          // {
          //   label: '人员姓名',
          //   prop: 'name',
          //   value: 'name',
          //   type: 'input' // 输入框类型
          // },
          // {
          //   label: '学工号',
          //   prop: 'xgh',
          //   value: 'xgh',
          //   type: 'input'
          // },
          // {
          //   label: '学工号',
          //   prop: 'xgh',
          //   value: 'xgh',
          //   type: 'select',
          //   option: [
          //     {
          //       label: '测试1',
          //       value: 'ces1'
          //     }
          //   ]
          // }
        ], //展示框
        rules: {} //是否必填等校验
      },
      //传输给后端的数据-------弹框
      ruleForm: {}
    };
  },
  computed: {},
  watch: {},
  methods: {
    //多选
    handleSelectionChange(e) {
      console.log(e);

      this.$emit('multipleChoices', e);
    },

    //多选回显
    showSelectionChange(checkedrow, val) {
      this.$refs.multipleApiTable.clearSelection(); //清除回显

      setTimeout(() => {
        checkedrow.forEach((key) => {
          this.tableList.forEach((row) => {
            if (row[val] == key) {
              this.$refs.multipleApiTable.toggleRowSelection(row, true); // 回显
            }
          });
        });
      }, 500); // 适当调整延迟时间
    },

    //条数
    handleSizeChange(val) {
      this.inquiryForm.page = 1;
      this.inquiryForm.limit = val;
      this.getTable();
    },

    //页数
    handleCurrentChange(val) {
      this.inquiryForm.page = val;
      this.getTable();
    },

    //获取列表
    async getTable() {
      try {
        this.loading = true;
        // this.inquiryForm = { ...this.inquiryForm, ...this.formData };

        let myData = { ...this.inquiryForm, ...this.formData };
        const res = await this.api(myData);
        console.log(res, 'API 返回数据');

        if (res.code == 0) {
          // 手动解析 zData 路径（如 "data.data.records"）
          const paths = this.zData.split('.'); // ["res", "data", "data", "records"]
          let value = res;
          for (const path of paths) {
            value = value[path];
            if (value === undefined) break; // 防止路径错误导致报错
          }
          this.tableList = value;
          // 解析总数（动态路径）
          const totalPaths = this.zDataTotal.split('.'); // 例如 "data.data.total" → ["data", "data", "total"]
          let totalValue = res;
          for (const path of totalPaths) {
            if (totalValue == undefined) break;
            totalValue = totalValue[path];
          }
          this.total = totalValue || 0; // 防止 undefined
        }
      } catch (error) {
        console.error('API 调用失败:', error);
        this.loading = false;
      } finally {
        this.loading = false;
      }
    },

    //编辑--新增弹框
    //打开弹框--confingList表格配置文件
    openForm(confingList) {
      this.popConfing = confingList; //赋值

      //添加基础校验
      this.popConfing.formList.forEach((item, index) => {
        if (item.prop) {
          this.popConfing.rules[item.prop] = [
            item.type == 'input'
              ? { required: true, message: `请输入${item.label}`, trigger: 'blur' }
              : { required: true, message: `请选择${item.label}`, trigger: 'change' }
          ];
        }
      });

      console.log(this.popConfing);

      this.dialogVisible = true;
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // alert('submit!');
          console.log(this.ruleForm);
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.dialogVisible = false;
    }
  }
};
</script>

<style lang="scss" scoped>
.queryTable-box {
  width: 100%;
  height: 100%;

  .el_pagination_box {
    width: 100%;
    height: 71px;
    margin-top: 10px;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
</style>
